package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ShoppingMapper shoppingMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    /**
     * 提交订单
     * 1.判断DTO中的购物车 和 地址 是否为空 如果为空直接抛出异常
     * 2.给orders赋值 插入
     * 3.给Order_detail赋值插入
     * 4.清空购物车
     * 5.封装Vo 返回
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //1.判断DTO中的购物车 和 地址 是否为空 如果为空直接抛出异常
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCarts = shoppingMapper.list(shoppingCart);
        if (shoppingCarts.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //检验地址是否超出送货范围
        checkOutOfRange(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        // 给orders赋值 插入
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setAddress(addressBook.getDetail());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(shoppingCart.getUserId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPayStatus(Orders.UN_PAID);

        //插入数据
        ordersMapper.insert(orders);
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();

        //3.给Order_detail赋值插入
        for (ShoppingCart cart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insert(orderDetails);
        //4.清空购物车
        shoppingMapper.deleteShoppingCartById(shoppingCart.getUserId());

        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        log.info("来单提醒");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type",1);//1表示来单提醒
        jsonObject.put("orderId",orders.getId());
        jsonObject.put("content","订单号"+outTradeNo);
        webSocketServer.sendToAllClient(jsonObject.toString());
    }
    //测试
/*    @Scheduled(cron = "0/5 * * * * ?")
    public void testWebSocket(){
        log.info("来单提醒");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type",1);//1表示来单提醒
        jsonObject.put("orderId",1);
        jsonObject.put("content","订单号"+1);
        webSocketServer.sendToAllClient(jsonObject.toString());
    }*/

    /**
     * 历史全部订单
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult historyOrders(Integer page, Integer pageSize, Integer status) {
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setPage(page);
        ordersPageQueryDTO.setPageSize(pageSize);
        ordersPageQueryDTO.setStatus(status);
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        //设置分页
        PageHelper.startPage(page, pageSize);
        //分页查询
        Page<Orders> orders = ordersMapper.pageQueryById(ordersPageQueryDTO);

        List<Orders> result = orders.getResult();

        ArrayList<OrderVO> list = new ArrayList<>();

        if (result != null && result.size() > 0) {
            for (Orders orders1 : result) {
                OrderVO orderVO = new OrderVO();
                Long orderId = orders1.getId();
                //查询订单详情
                List<OrderDetail> orderDetails = orderDetailMapper.pageQueryById(orderId);
                BeanUtils.copyProperties(orders1, orderVO);
                orderVO.setOrderDetailList(orderDetails);
                list.add(orderVO);
            }
        }
        return new PageResult(orders.getTotal(), list);
    }

    /**
     * 查询订单详情
     * 1.查询订单表
     * 2.查询订单详情表
     * 3.封装到vo返回
     *
     * @param id
     * @return
     */
    public OrderVO queryOrderById(Long id) {
        //1.查询订单表
        Orders orders = ordersMapper.queryById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);

        //2.查询订单详情表
        List<OrderDetail> orderDetails = orderDetailMapper.queryById(orders.getId());

        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 取消订单
     * - 待支付和待接单状态下，用户可直接取消订单
     * - 商家已接单状态下，用户取消订单需电话沟通商家
     * - 派送中状态下，用户取消订单需电话沟通商家
     * - 如果在待接单状态下取消订单，需要给用户退款
     * - 取消订单后需要将订单状态修改为“已取消”
     *
     * @param id
     */
    public void cancel(Long id) {
        Orders orders = ordersMapper.queryById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Integer status = orders.getStatus();
        if (status > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if (status == 2) {
            orders.setPayStatus(Orders.REFUND);
        }
        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }

    /**
     * 管理端订单查询
     * 1.分页查询
     * 2.查询出订单信息
     * 3.查询订单详情
     * 4.根据需求把菜品信息用Sting类型显示
     * 5.封装返回
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = ordersMapper.pageQueryById(ordersPageQueryDTO);
        ArrayList<OrderVO> list = new ArrayList<>();
        List<Orders> result = page.getResult();
        for (Orders orders : result) {
            OrderVO orderVO = new OrderVO();
            Long id = orders.getId();
            List<OrderDetail> orderDetails = orderDetailMapper.queryById(id);
/*            String orderDish = "";
            for (OrderDetail orderDetail : orderDetails) {
                orderDish = orderDish + orderDetail.getName() + "*" + orderDetail.getNumber() + ";";
            }*/
            String orderDishesStr = getOrderDishesStr(orders);

            BeanUtils.copyProperties(orders, orderVO);
/*            orderVO.setOrderDishes(orderDish);*/
            orderVO.setOrderDishes(orderDishesStr);
            list.add(orderVO);
        }
        return new PageResult(page.getTotal(), list);
    }
    private String getOrderDishesStr(Orders orders){
        //查询订单菜品详情（订单中菜品和数量）
        List<OrderDetail> orderDetails = orderDetailMapper.queryById(orders.getId());
        List<String> orderDishList = orderDetails.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());
        return String.join("",orderDishList);
    }



    /**
     * 统计各个状态订单的数量
     *
     * @return
     */
    public OrderStatisticsVO statistics() {
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        Page<Orders> orders = ordersMapper.pageQueryById(ordersPageQueryDTO);
        Integer confirmed = 0;
        Integer deliveryInProgress = 0;
        Integer toBeConfirmed = 0;
        for (Orders order : orders) {
            if (order.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
                toBeConfirmed += 1;
            } else if (order.getStatus().equals(Orders.CONFIRMED)) {
                confirmed += 1;
            } else if (order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
                deliveryInProgress += 1;
            }
        }
        OrderStatisticsVO statisticsVO = new OrderStatisticsVO();
        statisticsVO.setConfirmed(confirmed);
        statisticsVO.setDeliveryInProgress(deliveryInProgress);
        statisticsVO.setToBeConfirmed(toBeConfirmed);
        return statisticsVO;
    }

    /**
     * 再来一单
     * 1.根据订单id查出订单信息
     * 2.拷贝到shoppingCart
     * 3.根据查询到的订单信息查询订单详情
     * 4.遍历拷贝到shoppingCart
     *
     * @param id
     */
    public void repetition(Long id) {
        //1.根据订单id查出订单信息
        Orders orders = ordersMapper.queryById(id);
        ShoppingCart shoppingCart = new ShoppingCart();
        //2.拷贝到shoppingCart
        BeanUtils.copyProperties(orders, shoppingCart);
        // 3.根据查询到的订单信息查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.queryById(orders.getId());
        //4.遍历拷贝到shoppingCart
        for (OrderDetail orderDetail : orderDetails) {
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingMapper.insert(shoppingCart);
        }

    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
/*        Orders orders = ordersMapper.queryById1(ordersConfirmDTO.getId());
        orders.setStatus(OrderVO.CONFIRMED);
        ordersMapper.update(orders);*/
        //优化
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();

        ordersMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    public void rerejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders order = ordersMapper.queryById(ordersRejectionDTO.getId());
        if (order.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            order.setStatus(Orders.CANCELLED);
            order.setRejectionReason(ordersRejectionDTO.getRejectionReason());
            if (order.getPayStatus().equals(Orders.PAID)){
                order.setPayStatus(Orders.REFUND);
            }
            ordersMapper.update(order);
        }

    }

    /**
     * 管理端取消订单
     * @param ordersCancelDTO
     */
    public void cancelAdmin(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = ordersMapper.queryById(ordersCancelDTO.getId());
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLED);
        if (orders.getPayStatus().equals(Orders.PAID)){
            orders.setPayStatus(Orders.REFUND);
        }
        ordersMapper.update(orders);
    }

    /**
     * 派送
     * 1.根据id查询订单信息
     *  仅有接单的才能派送
     * 2.new一个新的订单 赋值 id 更改状态（增加数据库效率）
     * 3.更新
     * @param id
     */
    public void delivery(Long id) {
        Orders ordersDB = ordersMapper.queryById(id);
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        ordersMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    public void complete(Long id) {
        Orders ordersDB = ordersMapper.queryById(id);
        if (ordersDB==null&& !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }

    @Override
    public void reminder(Long id) {
        Orders orders = ordersMapper.queryById(id);
        log.info("来单提醒");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type",2);//1表示来单提醒
        jsonObject.put("orderId",orders.getId());
        jsonObject.put("content","订单号"+orders.getNumber());
        webSocketServer.sendToAllClient(jsonObject.toString());
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }
}
